
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../api/DictApi.dart';
import '../../../utils/Settings.dart';
import '../../../utils/StoreData.dart';
import '../../../utils/Utils.dart';
import '../../form/LFormLogic.dart';
import '../../get/MyController.dart';
import 'LFormSelectState.dart';


class LFormSelectLogic extends MyController{


  final state = LFormSelectState();

  void init({required Map formItem,required Map formData,String? betweenSign,required String formTag,required String formType}){
    state.formItem = formItem;
    state.formData = formData;
    state.defaultText = "";
    state.resultOptions = [];
    state.dictOptions = [];
    state.slectedIndex = -1;
    state.betweenSign = betweenSign??"";
    state.formTag = formTag;
    state.formType = formType;

    //初始化下拉数据
    initDict();
  }

  ///初始化下拉数据
  initDict()async{
    ///是否人为给了下拉信息
    if(!Utils.isEmpty(state.formItem["options"])){
      state.dictOptions = state.formItem["options"];
      initDefaultValue();
      update();
      return;
    }

    if(Utils.isEmpty(state.formItem["dictCode"])){
      return;
    }
    //初始化数据字典信息
    List dictCodeReplaceFields = [];
    if(!Utils.isEmpty(state.formItem['replaceFields'])){
      dictCodeReplaceFields.add({'dictCode':'${state.formItem["dictCode"]}','replaceFields':state.formItem['replaceFields']});
    }
    await DictApi.initDict(state.formItem["dictCode"], "", dictCodeReplaceFields);
    state.resultOptions = StoreData.dictInfo[state.formItem["dictCode"]];
    state.dictOptions = state.resultOptions;
    initDefaultValue();
    update();
  }

  initDefaultValue(){
    if(state.formData['${state.formItem["field"]}${state.betweenSign}']!=null){
      //说明有默认值
      for(int i=0;i<state.dictOptions.length;i++ ){
        if(state.dictOptions[i]["itemValue"]==state.formData['${state.formItem["field"]}${state.betweenSign}']){
          state.defaultText = state.dictOptions[i]["itemText"];
          state.slectedIndex = i;
          break;
        }
      }
    }
  }




  //当数据字典编号发生变化
  void updateDictCode() async{
    if(Utils.isEmpty(state.formItem["dictCode"])){
      return;
    }
    //初始化数据字典信息
    List dictCodeReplaceFields = [];
    if(state.formItem['replaceFields']!=null){
      dictCodeReplaceFields.add({'dictCode':'${state.formItem["dictCode"]}','replaceFields':state.formItem['replaceFields']});
    }
    await DictApi.initDict(state.formItem["dictCode"], "", dictCodeReplaceFields);
    state.resultOptions = StoreData.dictInfo[state.formItem["dictCode"]];
    state.dictOptions = state.resultOptions;
    initDefaultValue();
    update();
  }




  dynamic onValidator(v){
    //非空验证
    if (state.formItem["required"] == true && (v == null || v.isEmpty || v.trim().isEmpty)) {
      return "${state.formItem["label"]}不能为空";
    }
    return null;
  }

  //清空选择
  void onClear(){
    //清空选择的内容
    state.formData['${state.formItem["field"]}${state.betweenSign}'] = null;
    state.slectedIndex = -1;
    state.defaultText = "";
    if(state.formType==Settings.formType["表单"]){
      Get.find<LFormLogic>(tag: state.formTag).onChange({'field':'${state.formItem["field"]}${state.betweenSign}','val':null});
    }
    update();
  }

  //选择
  void onSelected(optionItem,index){
    state.formData['${state.formItem["field"]}${state.betweenSign}'] = optionItem["itemValue"];
    state.defaultText = optionItem["itemText"];
    state.slectedIndex = index;
    if(state.formType==Settings.formType["表单"]){
      // Get.put(LFormLogic(),tag:state.formTag).onChange({'field':'${state.formItem["field"]}${state.betweenSign}','val':optionItem["itemValue"]});
      Get.find<LFormLogic>(tag: state.formTag).onChange({'field':'${state.formItem["field"]}${state.betweenSign}','val':optionItem["itemValue"]});
    }
    update();
  }

  Future<dynamic> showCustomModalBottomSheet(context, tag) async {
    if(state.dictOptions.isEmpty){
      return null;
    }
    return showModalBottomSheet<dynamic>(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {

        return Container(
          clipBehavior: Clip.antiAlias,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.0),
              topRight: Radius.circular(20.0),
            ),
          ),
          height: MediaQuery.of(context).size.height / 2.0,
          child: Column(children: [
            SizedBox(
              height: 50,
              child: Stack(
                textDirection: TextDirection.rtl,
                children: [
                  Align(
                    alignment: Alignment.topLeft,
                    child: IconButton(
                      icon: const Icon(Icons.delete_forever_rounded),
                      onPressed: () {
                        Get.back();
                        onClear();
                      }),
                  ),
                  Center(
                    child: Text(
                      '${state.formItem["label"]}选择',
                      style: const TextStyle(
                          fontWeight: FontWeight.bold, fontSize: 16.0),
                    ),
                  ),
                  IconButton(
                      icon: const Icon(Icons.close),
                      onPressed: () {
                        Get.back();
                      }),
                ],
              ),
            ),
            const Divider(height: 1.0),
            Expanded(
              child: ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                      title: Text(state.dictOptions[index]["itemText"]),
                      selected: state.slectedIndex==index,
                      onTap: () {
                        onSelected(state.dictOptions[index],index);
                        Get.back();
                      });
                },
                itemCount: state.dictOptions.length,
              ),
            ),
          ]),
        );
      },
    );
  }

  ///如果是QUERYFORM 重置，需要将显示值清空
  @override
  void reset(){
    state.defaultText="";
    update();
  }
}

